import os.path
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
from google.appengine.api import channel
from django.utils import simplejson as json
from model import *
import os
import logging

class BaseRequestHandler(webapp.RequestHandler):
    """Supplies a common template generation function.

  When you call write_out(), we augment the template variables supplied with
  the current user in the 'user' variable and the current webapp request
  in the 'request' variable.
  """
    def write_out(self, template_name, template_values={}):
        values = {
            'user'      : users.get_current_user(),
            'admin_user': users.is_current_user_admin(),
            'logout_url': users.create_logout_url(self.request.uri),
            'events'    : Event.events(),
            'page_title': 'CollabarotiVe'
        }
        values.update(template_values)
        self.response.out.write(self.generate(template_name, values))

    def generate(self, template_name, values):
        directory = os.path.dirname(__file__)
        path      = os.path.join(directory, os.path.join('templates', template_name))
        return template.render(path, values, debug=True)

    def _check_user(self):
        if not Member.exists():
            if users.is_current_user_admin():
                member = Member(user=users.get_current_user())
                member.status = 'accepted'
                member.put()
            else:
                if not os.environ['PATH_INFO'] == '/projects':
                    self.redirect('/projects')
        
    def get(self):
        self._check_user()
        try:
            self._get()
        except AttributeError:
            self.response.out.write("Bad id!!!, your id is not correct.")
            logging.exception("Bad id!!!, your id is not correct.")
        except Exception:
            self.response.out.write("Something is wrong, we will try to figure out it.")
            logging.exception("Something is wrong, we will try to figure out it.")


    def post(self):
        self._check_user()
        self._post()

    def json_response(self, response):
        jsonr = json.dumps(response)
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.out.write(jsonr)
        
    def not_allowed_error(self):
        url = self.request.uri
        self.write_out('not_allowed.html', {
                      'url': url
                      })

        
class Observable():
    def __init__(self, room):
        self._room = room
        self._observers = memcache.get(self._room)

    def add_observer(self, user):
        if self._observers is not None:
            self._observers.update(user)
        else:
            self._observers = user

        if not memcache.set(self._room, self._observers, 30*60):
            logging.error("Memcache set failed.")

    def delete_observer(self):
        pass
    def notify_observers(self, data):
        for channel_id in self._observers.values():
            channel.send_message(channel_id, data)